﻿Imports System
Imports System.Threading
Imports System.Runtime.InteropServices
Imports DotNetNuke.Light

Public Class Proxy

    Private Shared AuthToken As String
    Private duration As New System.TimeSpan(0)
    Public Property LastCallDuration() As System.TimeSpan
        Get
            Return duration
        End Get
        Set(ByVal value As System.TimeSpan)
            duration = value
        End Set
    End Property

    Public Function SendRequest(ByVal Request As Common.Request) As Common.Response

        Dim sendStr As String

        If Not (AuthToken Is Nothing) Then
            Request.Connection.Credential.AuthToken = AuthToken
            Request.Connection.Credential.UserName = Nothing
            Request.Connection.Credential.Password = Nothing

        End If


        Dim json As New System.Web.Script.Serialization.JavaScriptSerializer()
        sendStr = json.Serialize(Request)

        Console.WriteLine("REQUEST:" + sendStr)
        Dim response As String

        Dim wc As New System.Net.WebClient()
        wc.Headers.Add("Content-Type", "application/json; charset=utf-8")
        Dim dt As DateTime = DateTime.Now

        response = wc.UploadString(Request.Connection.Server.ServerUri, sendStr)
        LastCallDuration = New TimeSpan(DateTime.Now.Ticks - dt.Ticks)


        Console.WriteLine("RESPONSE:" + response)

        Dim r As Common.Response = json.Deserialize(Of Common.Response)(response)

        If (AuthToken Is Nothing) Then AuthToken = r.AuthToken

        Return r

    End Function

End Class


Public Class MyWebClient
    Inherits System.Net.WebClient

    Public _CookiesRequest As System.Net.CookieContainer
    Public _CookiesResponse As System.Net.CookieCollection
    Public Function GetRequest(ByVal address As System.Uri) As System.Net.WebRequest
        Return GetWebRequest(address)
    End Function
    Public Function GetResponse(ByVal request As System.Net.WebRequest, ByVal result As System.IAsyncResult) As System.Net.WebResponse
        Return GetWebResponse(request, result)
    End Function

    Protected Overrides Function GetWebRequest(ByVal address As System.Uri) As System.Net.WebRequest
        Dim request As System.Net.HttpWebRequest = DirectCast(MyBase.GetWebRequest(address), System.Net.HttpWebRequest)
        request.CookieContainer = _CookiesRequest
        Return request
    End Function

    Protected Overrides Function GetWebResponse(ByVal request As System.Net.WebRequest, ByVal result As System.IAsyncResult) As System.Net.WebResponse
        Dim response As System.Net.HttpWebResponse = DirectCast(MyBase.GetWebResponse(request, result), System.Net.HttpWebResponse)
        _CookiesResponse = response.Cookies
        Return response
    End Function
End Class